package app.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import app.config.Config;
import app.domain.FileInfo;
import app.domain.Result;
import app.service.FileService;
import app.utils.FileUtil;

@Controller
@RequestMapping("file")
public class FileController {
	@Autowired
	private FileService fileService;
	
    @RequestMapping(value="/upload")
    @ResponseBody
	public Result doUploadFile(HttpServletRequest request,@RequestParam("file") MultipartFile file){
    	Result result=new Result(Config.FAIL_CODE,"");
		if(!file.isEmpty()){
	    	String path=Config.UPLOAD_FILE_REAL_PATH;
	    	String fileName=System.currentTimeMillis()+ file.getOriginalFilename();
	    	FileInfo fileInfo=new FileInfo(Config.UPLOAD_FILE_PATH,fileName);
			try {
				FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path,fileName));
			    result.setCode(Config.SUCCESS_CODE);
			    result.setMessage("上传成功");
			} catch (IOException e) {
				e.printStackTrace();
				result.setCode(Config.FAIL_CODE);
				return result;
			}
			int fileId=fileService.addFileInfo(fileInfo);
			fileInfo.setId(fileId);
			fileInfo.setWebPath(FileUtil.getFileWebPath(Config.UPLOAD_FILE_PATH,fileName));
			result.setRow(fileInfo);
		}
		
		return result;
	}
    
  
}
